package sesion;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import com.google.appengine.api.datastore.Key;

import entity.Korisnik;
import entity.Kupac;

public class KupacDaoJpa extends GenericJpaDao<Kupac, Key> implements KupacDao{
	
	public Korisnik ulogujKupca(String korisnickoIme,String sifra)
	{
		Korisnik korisnik=null;
		EntityManager em = null;
	    try {
	        em = emf.createEntityManager();
	        Query query = em.createQuery("select m from " + persistentClass.getSimpleName()+" m where m.koisnickoIme='"+korisnickoIme+"' and m.korisnickaSifra='"+sifra+"'");
	        korisnik=(Kupac)query.getSingleResult();
	    }
	    catch(NoResultException ex)
	    {
	    	
	    }
	    catch (Exception ex) {
	        ex.printStackTrace();
	    }
	    
	    finally
	    {
	    	if(em.isOpen())
	    	{
	    		em.close();
	        }
	    }
		return korisnik;
	}
	
	public void izbrisiKupca(String pom) {
		EntityManager em = null;
	    EntityTransaction tx = null;
	    Kupac kupac=null;
	    try {
	        em = emf.createEntityManager();
	        Query query = em.createQuery("select m from " + persistentClass.getSimpleName()+" m where m.koisnickoIme='"+pom+"'");
	        kupac=(Kupac)query.getSingleResult();
	        if(kupac!=null)
	        {
	        	tx = em.getTransaction();
		        tx.begin();
	        	em.remove(kupac);
	        	tx.commit();
	        }
	    }
	    catch(NoResultException ex)
	    {
	    	
	    }
	    catch (Exception ex) {
	    	ex.printStackTrace();
	        if (tx != null) {
	        tx.rollback();
	        }
	    }
	    finally
	    {
	    	em.close();
	    }
	}
	
	public Kupac pronadjiKupaca(String korisnickoIme)
	{
		Kupac kupac=null;
		EntityManager em = null;
	    try {
	        em = emf.createEntityManager();
	        Query query = em.createQuery("select m from " + persistentClass.getSimpleName()+" m where m.koisnickoIme='"+korisnickoIme+"'");
	        kupac=(Kupac)query.getSingleResult();
	    }
	    catch(NoResultException ex)
	    {
	    	
	    }
	    catch (Exception ex) {
	        ex.printStackTrace();
	    }
	    
	    finally
	    {
	    	em.close();
	    }
		return kupac;
	}
}
